#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<time.h>
#include"BlockingQueue.hpp"
#include"Task.hpp"

using namespace std;

void* Producer(void* args)
{
    PCmode::BlockQueue<PCmode::Task<int>>* bq=static_cast<PCmode::BlockQueue<PCmode::Task<int>>*>(args);

    std::string opers="+-*/%";

    while(true)
    {
        //生产商品
        int x=rand()%100;
        int y=rand()%100;

        char ops[]={'+','-','*','/','%'};
        char op=ops[rand()%opers.size()];
        //将商品推送至阻塞队列中
        bq->Push(PCmode::Task<int>(x,y,op));

        cout<<"生产者生产了"<<"x"<<"op"<<"y"<<endl;
        cout<<"-------------------------------------"<<endl;
    }
    pthread_exit((void*)0);
}

void* Consumer(void* args)
{
    PCmode::BlockQueue<PCmode::Task<int>>* bq=static_cast<PCmode::BlockQueue<PCmode::Task<int>>*>(args);

    while(true)
    {
        //将商品从阻塞队列中取出
        PCmode::Task<int> task;
        bq->Pop(&task);
        task();

        string ret=task.getResult();
        //消费商品
        cout<<"消费者消费了一个对象，其结果为"<<ret<<endl;
        cout<<"-------------------------"<<endl;
    }
    pthread_exit((void*)0);
}

int main()
{
    //创建一个阻塞队列
    PCmode::BlockQueue<int>* bq=new PCmode::BlockQueue<int>;
    //创建生产和消费者线程
    pthread_t pro,con;
    pthread_create(&pro,nullptr,Producer,bq);
    pthread_create(&con,nullptr,Consumer,bq);

    //等待线程结束
    pthread_join(pro,nullptr);
    pthread_join(con,nullptr);

    delete(bq);
    return 0;
}